<template>
  <select 
    :value="modelValue" 
    @change="handleChange"
    :disabled="disabled"
    class="dict-select">
    <option v-if="placeholder" value="">{{ placeholder }}</option>
    <option 
      v-for="item in options" 
      :key="item.dictValue" 
      :value="item.dictValue">
      {{ item.dictLabel }}
    </option>
  </select>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { dictUtil } from '@/utils/dict'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  dictType: {
    type: String,
    required: true
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const options = ref([])
const loading = ref(false)

// 加载字典数据
const loadDict = async () => {
  loading.value = true
  try {
    const data = await dictUtil.getDictData(props.dictType)
    options.value = data
  } catch (error) {
    console.error('加载字典数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理值变化
const handleChange = (event) => {
  const value = event.target.value
  emit('update:modelValue', value)
  emit('change', value)
}

// 监听字典类型变化
watch(() => props.dictType, loadDict, { immediate: true })

onMounted(() => {
  loadDict()
})
</script>

<style scoped>
.dict-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.dict-select:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.dict-select:focus {
  outline: none;
  border-color: #3b82f6;
}
</style>